/*
 * A collection of helper functions
 */

/*
 *	Returns a copy of the object using the jQuery.extend() method
 */
function clone(oldObj) {
    return jQuery.extend({}
    /* clone */
    , oldObj);
}

/*
 * datetime Helpers ===============================
 */

/*
 * makes relative time out of "Sun Jul 08 19:01:12 +0000 2007" type string
 * Borrowed from Mike Demers (slightly altered)
 * https://twitter.pbwiki.com/RelativeTimeScripts
 */
function get_relative_time(time_value) {
    var parsed_date = new Date(time_value);
    var now = new Date;
    var delta = parseInt((now.getTime() - parsed_date.getTime()) / 1000);

    if (delta < 10) {
        return 'Just now';
    } else if (delta < 60) {
        return delta.toString() + ' sec ago';
    } else if (delta < 120) {
        return '1 min ago';
    } else if (delta < (45 * 60)) {
        return Math.round(parseInt(delta / 60)).toString() + ' min ago';
    } else if (delta < (90 * 60)) {
        return '1 hr ago';
    } else if (delta < (24 * 60 * 60)) {
        if (Math.round(delta / 3600) == 1) {
            return '2 hr ago';
        } else {
            return Math.round(delta / 3600).toString() + ' hr ago';
        }
    } else if (delta < (48 * 60 * 60)) {
        return '1 day ago';
    } else {
        return Math.round(delta / 86400).toString() + ' days ago';
    }
}

function httpTimeToInt(entryDate) {
    var parsedDate = new Date;
    parsedDate.setTime(Date.parse(entryDate));
    return parsedDate.getTime();
}

function getTimeAsInt() {
    var now = new Date;
    return now.getTime();
}

/*
 * jQuery Helpers ==================================
 */
jQuery.extend(jQuery.expr[':'], {
    icontains: function(a, i) {
        return (a.textContent || a.innerText || jQuery(a).text() || '').toLowerCase().indexOf((m[3] || '').toLowerCase()) >= 0;
    }
});

/*
 * JSON Helpers ====================================
 */

/*
 * A wrapper for JSON that correct Twitter issues and perform logging if JSON data could not be parsed
 * which will help to find out what is wrong
 */
function parseJSON(text) {
    // Fix twitter data bug
    var re = new RegExp("Couldn\\'t\\ find\\ Status\\ with\\ ID\\=[0-9]+\\,", "g");
    text = text.replace(re, "");

    var done = false
    try {
        var obj = JSON.parse(text);
        done = true;
    }
    finally {
        if (!done) {
            Skink.dump("Could not parse JSON text " + text);
        }
    }

    return obj;
}